$(function(){
    $(window).on("load",()=>{
        class Login{
            constructor(){
                this.username  = $("#username");
                this.password  = $("#password");
                this.login_btn = $("#login_btn")
                this.alert = $("#login-alert");

                this.usermsg = JSON.parse(sessionStorage.getItem("usermsg"));
                if(this.usermsg !== null){
                    this.writeUserMsg();
                }

                this.bindEvent();
            } 
       
            //注册界面的值传入
            writeUserMsg(){
                this.username.val(this.usermsg.username)
                this.password.val(this.usermsg.password)
            }
          

            bindEvent(){
                this.login_btn.click(()=>{
                    this.login();
                }) 
                
            }
            login(){
               
                var _this = this;
               
                $.ajax({
                    url: "http://127.0.0.1:8888/users/login",
                    data: {
                        username: this.username.val(),
                        password: this.password.val(),
                    },
                    type: "POST",
                    dataType: "json"
                }).done(function(res){
                    switch (res.code){
                        case 0 :
                            _this.error(res);
                            break;
                        case 1:
                            _this.success(res);
                            break;
                    }
                })
            }
            success(res){
                this.alert.removeClass("login-alert-success", "login-alert-danger");
                this.alert.addClass("login-alert-success");
                this.alert.html("恭喜登陆成功稍后我们将为您跳转到首页");
                setTimeout(() => {
                    cookie("TOKEN", res.token);
                    cookie("ID", res.user.id);
            
                    location.href = "./index.html";
                  }, 3000);
            }
            error(res){
                this.alert.removeClass("login-alert-success", "login-alert-danger");
                this.alert.addClass("login-alert-danger");
                this.alert.html("抱歉登录失败 : " + res.message);
          
                setTimeout(() => {
                  this.alert.removeClass("login-alert-success", "login-alert-danger");
                }, 2000);
            }
           
        }

        new Login
    })
   
})